<template>
  <div class="app-container">
    <!-- 筛选区域 -->
    <el-card shadow="never" class="filter-container">
      <el-form :inline="true" :model="filterForm" ref="filterFormRef">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="科室">
          <el-select v-model="filterForm.departmentId" placeholder="请选择科室" clearable>
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收入类型">
          <el-select v-model="filterForm.incomeType" placeholder="请选择收入类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="挂号费" value="registration" />
            <el-option label="处方费" value="prescription" />
            <el-option label="检查费" value="examination" />
            <el-option label="治疗费" value="treatment" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-title">总收入</div>
          <div class="stats-value">¥{{ formatNumber(statistics.totalIncome) }}</div>
          <div class="stats-compare">
            <span>同比：</span>
            <span :class="statistics.yearCompare >= 0 ? 'up' : 'down'">
              <el-icon v-if="statistics.yearCompare >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(statistics.yearCompare || 0).toFixed(2) }}%
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-title">日均收入</div>
          <div class="stats-value">¥{{ formatNumber(statistics.avgDailyIncome) }}</div>
          <div class="stats-compare">
            <span>环比：</span>
            <span :class="statistics.monthCompare >= 0 ? 'up' : 'down'">
              <el-icon v-if="statistics.monthCompare >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(statistics.monthCompare || 0).toFixed(2) }}%
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-title">人均消费</div>
          <div class="stats-value">¥{{ formatNumber(statistics.avgPerPatient) }}</div>
          <div class="stats-compare">
            <span>同比：</span>
            <span :class="statistics.avgPerPatientCompare >= 0 ? 'up' : 'down'">
              <el-icon v-if="statistics.avgPerPatientCompare >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(statistics.avgPerPatientCompare || 0).toFixed(2) }}%
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-title">收费记录数</div>
          <div class="stats-value">{{ formatNumber(statistics.totalPayments) }}</div>
          <div class="stats-compare">
            <span>同比：</span>
            <span :class="statistics.paymentsCompare >= 0 ? 'up' : 'down'">
              <el-icon v-if="statistics.paymentsCompare >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(statistics.paymentsCompare || 0).toFixed(2) }}%
            </span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收入趋势图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>收入趋势分析</span>
              <div class="chart-tools">
                <el-radio-group v-model="trendType" size="small" @change="loadIncomeTrend">
                  <el-radio-button label="daily">日</el-radio-button>
                  <el-radio-button label="weekly">周</el-radio-button>
                  <el-radio-button label="monthly">月</el-radio-button>
                </el-radio-group>
                <el-select v-model="trendDataType" size="small" @change="loadIncomeTrend" style="margin-left: 10px;">
                  <el-option label="总量" value="total" />
                  <el-option label="分类" value="category" />
                </el-select>
              </div>
            </div>
          </template>
          <div class="chart-container" v-loading="trendChartLoading">
            <div ref="trendChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收入分布图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>收入类型分布</span>
            </div>
          </template>
          <div class="chart-container" v-loading="categoryChartLoading">
            <div ref="categoryChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>支付方式分布</span>
            </div>
          </template>
          <div class="chart-container" v-loading="paymentMethodChartLoading">
            <div ref="paymentMethodChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 科室和医生收入排行 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>科室收入排行</span>
            </div>
          </template>
          <div class="chart-container" v-loading="deptChartLoading">
            <div ref="deptChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>医生收入排行</span>
            </div>
          </template>
          <div class="chart-container" v-loading="doctorChartLoading">
            <div ref="doctorChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 药品收入统计 -->
    <el-row class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>药品收入TOP 10</span>
              <el-radio-group v-model="drugStatType" size="small" @change="loadDrugStats">
                <el-radio-button label="cost">收入金额</el-radio-button>
                <el-radio-button label="count">销售次数</el-radio-button>
                <el-radio-button label="amount">销售数量</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" v-loading="drugChartLoading">
            <div ref="drugChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { statisticsAPI, departmentAPI } from '@/utils/api'
import * as echarts from 'echarts/core'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的 ECharts 组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  LineChart,
  BarChart,
  PieChart,
  CanvasRenderer
])

// 筛选表单
const filterFormRef = ref(null)
const filterForm = reactive({
  dateRange: [],
  departmentId: '',
  incomeType: ''
})

// 下拉选项
const departmentOptions = ref([])

// 图表参数
const trendType = ref('daily')
const trendDataType = ref('total')
const drugStatType = ref('cost')

// 图表引用
const trendChartRef = ref(null)
const categoryChartRef = ref(null)
const paymentMethodChartRef = ref(null)
const deptChartRef = ref(null)
const doctorChartRef = ref(null)
const drugChartRef = ref(null)

// 图表实例
let trendChart = null
let categoryChart = null
let paymentMethodChart = null
let deptChart = null
let doctorChart = null
let drugChart = null

// 加载状态
const trendChartLoading = ref(false)
const categoryChartLoading = ref(false)
const paymentMethodChartLoading = ref(false)
const deptChartLoading = ref(false)
const doctorChartLoading = ref(false)
const drugChartLoading = ref(false)

// 统计数据
const statistics = reactive({
  totalIncome: 283650,
  avgDailyIncome: 9455,
  avgPerPatient: 487.5,
  totalPayments: 4120,
  yearCompare: 12.8,
  monthCompare: 5.3,
  avgPerPatientCompare: 7.2,
  paymentsCompare: 9.4
})

// 日期快捷选项
const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 初始化日期范围为最近30天
const initDateRange = () => {
  const end = new Date()
  const start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
  filterForm.dateRange = [formatDate(start), formatDate(end)]
}

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 格式化数字
const formatNumber = (num) => {
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

// 搜索
const handleSearch = () => {
  fetchStatistics()
  loadIncomeTrend()
  loadIncomeTypeDistribution()
  loadPaymentMethodDistribution()
  loadDepartmentRank()
  loadDoctorRank()
  loadDrugStats()
}

// 重置搜索
const resetSearch = () => {
  filterFormRef.value.resetFields()
  initDateRange()
  handleSearch()
}

// 获取统计概览数据
const fetchStatistics = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  try {
    const params = {
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1],
      departmentId: filterForm.departmentId,
      incomeType: filterForm.incomeType,
      groupBy: 'summary'
    }
    
    const res = await statisticsAPI.getIncomeStatsSummary(params)
    if (res.success && res.data) {
      const data = res.data
      
      statistics.totalIncome = data.totalIncome || 0
      statistics.avgDailyIncome = data.avgDailyIncome || 0
      statistics.avgPerPatient = data.avgPerPatient || 0
      statistics.totalPayments = data.totalPayments || 0
      statistics.yearCompare = data.yearCompare || 0
      statistics.monthCompare = data.monthCompare || 0
      statistics.avgPerPatientCompare = data.avgPerPatientCompare || 0
      statistics.paymentsCompare = data.paymentsCompare || 0
    }
  } catch (error) {
    console.error('获取统计概览数据失败', error)
  }
}

// 加载收入趋势数据
const loadIncomeTrend = async () => {
  try {
    trendChartLoading.value = true
    
    // 生成模拟数据
    const dates = []
    const totalData = []
    const categoryData = {
      registration: [],
      prescription: [],
      examination: [],
      treatment: [],
      other: []
    }
    
    // 根据选择的时间粒度生成数据
    if (trendType.value === 'daily') {
      // 生成30天的数据
      for (let i = 0; i < 30; i++) {
        const date = new Date()
        date.setDate(date.getDate() - (29 - i))
        dates.push(formatDate(date))
        
        const total = Math.floor(Math.random() * 5000) + 8000
        totalData.push(total)
        
        // 各分类收入
        categoryData.registration.push(Math.floor(total * 0.15))
        categoryData.prescription.push(Math.floor(total * 0.35))
        categoryData.examination.push(Math.floor(total * 0.25))
        categoryData.treatment.push(Math.floor(total * 0.15))
        categoryData.other.push(Math.floor(total * 0.1))
      }
    } else if (trendType.value === 'weekly') {
      // 生成12周的数据
      for (let i = 0; i < 12; i++) {
        const date = new Date()
        date.setDate(date.getDate() - (11 - i) * 7)
        dates.push(`第${i + 1}周`)
        
        const total = Math.floor(Math.random() * 30000) + 50000
        totalData.push(total)
        
        // 各分类收入
        categoryData.registration.push(Math.floor(total * 0.15))
        categoryData.prescription.push(Math.floor(total * 0.35))
        categoryData.examination.push(Math.floor(total * 0.25))
        categoryData.treatment.push(Math.floor(total * 0.15))
        categoryData.other.push(Math.floor(total * 0.1))
      }
    } else {
      // 生成12个月的数据
      for (let i = 0; i < 12; i++) {
        const date = new Date()
        date.setMonth(date.getMonth() - (11 - i))
        const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
        dates.push(monthNames[date.getMonth()])
        
        const total = Math.floor(Math.random() * 100000) + 200000
        totalData.push(total)
        
        // 各分类收入
        categoryData.registration.push(Math.floor(total * 0.15))
        categoryData.prescription.push(Math.floor(total * 0.35))
        categoryData.examination.push(Math.floor(total * 0.25))
        categoryData.treatment.push(Math.floor(total * 0.15))
        categoryData.other.push(Math.floor(total * 0.1))
      }
    }
    
    // 渲染趋势图
    if (!trendChart) {
      trendChart = echarts.init(trendChartRef.value)
    }
    
    let option
    
    if (trendDataType.value === 'total') {
      // 总量趋势图
      option = {
        title: {
          text: '收入趋势分析',
          left: 'center',
          textStyle: {
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          },
          formatter: '{b}<br />收入: ¥{c}'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '收入金额',
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        series: [
          {
            name: '收入',
            type: 'line',
            smooth: true,
            data: totalData,
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(128, 0, 128, 0.8)' },
                  { offset: 1, color: 'rgba(128, 0, 128, 0.1)' }
                ]
              }
            },
            itemStyle: {
              color: 'purple'
            },
            lineStyle: {
              width: 3
            },
            symbolSize: 8
          }
        ]
      }
    } else {
      // 分类趋势图
      option = {
        title: {
          text: '收入分类趋势分析',
          left: 'center',
          textStyle: {
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['挂号费', '药品费', '检查费', '治疗费', '其他'],
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '收入金额',
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        series: [
          {
            name: '挂号费',
            type: 'bar',
            stack: 'total',
            data: categoryData.registration,
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '药品费',
            type: 'bar',
            stack: 'total',
            data: categoryData.prescription,
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            name: '检查费',
            type: 'bar',
            stack: 'total',
            data: categoryData.examination,
            itemStyle: {
              color: '#E6A23C'
            }
          },
          {
            name: '治疗费',
            type: 'bar',
            stack: 'total',
            data: categoryData.treatment,
            itemStyle: {
              color: '#F56C6C'
            }
          },
          {
            name: '其他',
            type: 'bar',
            stack: 'total',
            data: categoryData.other,
            itemStyle: {
              color: '#909399'
            }
          }
        ]
      }
    }
    
    trendChart.setOption(option)
    window.addEventListener('resize', () => {
      trendChart && trendChart.resize()
    })
  } catch (error) {
    console.error('加载收入趋势数据失败:', error)
  } finally {
    trendChartLoading.value = false
  }
}

// 加载收入类型分布数据
const loadIncomeTypeDistribution = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  categoryChartLoading.value = true
  try {
    const params = {
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1],
      departmentId: filterForm.departmentId,
      incomeType: filterForm.incomeType,
      groupBy: 'category'
    }
    
    // 使用静态模拟数据
    const mockData = {
      success: true,
      data: {
        categories: ['挂号费', '药品费', '检查费', '治疗费', '其他'],
        amounts: [45800, 112500, 78300, 32000, 15050]
      }
    }
    
    renderCategoryChart(mockData.data)
  } catch (error) {
    console.error('获取收入类型分布数据失败', error)
  } finally {
    categoryChartLoading.value = false
  }
}

// 渲染收入类型分布图
const renderCategoryChart = (data) => {
  if (!categoryChart) {
    categoryChart = echarts.init(categoryChartRef.value)
  }
  
  const categories = data.categories || []
  const amounts = data.amounts || []
  
  // 准备饼图数据
  const pieData = categories.map((category, index) => ({
    name: category,
    value: amounts[index]
  }))
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: categories
    },
    series: [
      {
        name: '收入类型',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  }
  
  categoryChart.setOption(option)
  window.addEventListener('resize', () => categoryChart.resize())
}

// 加载支付方式分布数据
const loadPaymentMethodDistribution = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  paymentMethodChartLoading.value = true
  try {
    const params = {
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1],
      departmentId: filterForm.departmentId,
      incomeType: filterForm.incomeType,
      groupBy: 'paymentMethod'
    }
    
    // 使用静态模拟数据
    const mockData = {
      success: true,
      data: {
        methods: ['微信支付', '支付宝', '医保卡', '现金', '银行卡'],
        amounts: [128500, 86200, 42300, 15600, 11050]
      }
    }
    
    renderPaymentMethodChart(mockData.data)
  } catch (error) {
    console.error('获取支付方式分布数据失败', error)
  } finally {
    paymentMethodChartLoading.value = false
  }
}

// 渲染支付方式分布图
const renderPaymentMethodChart = (data) => {
  if (!paymentMethodChart) {
    paymentMethodChart = echarts.init(paymentMethodChartRef.value)
  }
  
  const methods = data.methods || []
  const amounts = data.amounts || []
  
  // 准备饼图数据
  const pieData = methods.map((method, index) => ({
    name: method,
    value: amounts[index]
  }))
  
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6B', '#909399']
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: methods
    },
    color: colors,
    series: [
      {
        name: '支付方式',
        type: 'pie',
        radius: '60%',
        center: ['40%', '50%'],
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  paymentMethodChart.setOption(option)
  window.addEventListener('resize', () => paymentMethodChart.resize())
}

// 加载科室收入排行数据
const loadDepartmentRank = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  deptChartLoading.value = true
  try {
    // 使用静态模拟数据
    const mockData = {
      success: true,
      data: {
        departments: [
          { departmentId: "D001", departmentName: "内科", totalAmount: 98500, orderCount: 980 },
          { departmentId: "D002", departmentName: "外科", totalAmount: 75800, orderCount: 750 },
          { departmentId: "D003", departmentName: "儿科", totalAmount: 55600, orderCount: 650 },
          { departmentId: "D004", departmentName: "妇产科", totalAmount: 62300, orderCount: 580 },
          { departmentId: "D005", departmentName: "骨科", totalAmount: 48900, orderCount: 430 },
          { departmentId: "D006", departmentName: "眼科", totalAmount: 42000, orderCount: 360 },
          { departmentId: "D007", departmentName: "口腔科", totalAmount: 38500, orderCount: 350 },
          { departmentId: "D008", departmentName: "皮肤科", totalAmount: 32400, orderCount: 290 }
        ]
      }
    }
    
    renderDeptChart(mockData.data)
  } catch (error) {
    console.error('获取科室收入排行数据失败', error)
  } finally {
    deptChartLoading.value = false
  }
}

// 渲染科室收入排行图
const renderDeptChart = (data) => {
  if (!deptChart) {
    deptChart = echarts.init(deptChartRef.value)
  }
  
  // 处理科室数据
  const departments = data.departments || []
  
  // 确保每个科室都有正确的数据
  const processedDepts = departments.map(dept => {
    let deptName = dept.departmentName || '未知科室';
    let value = dept.totalAmount || 0;
    
    return {
      department: deptName,
      value: value,
      id: dept.departmentId,
      orderCount: dept.orderCount || 0
    };
  });
  
  // 按收入金额排序
  const sortedData = processedDepts.sort((a, b) => b.value - a.value)
  
  // 取前10个科室
  const top10Data = sortedData.slice(0, 10)
  const deptNames = top10Data.map(item => item.department)
  const deptValues = top10Data.map(item => item.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const idx = params[0].dataIndex;
        const item = top10Data[idx];
        let tooltip = `${params[0].name}<br/>收入: ¥${params[0].value}`;
        
        if (item) {
          if (item.orderCount) {
            tooltip += `<br/>医嘱数量: ${item.orderCount}`;
          }
          if (item.id) {
            tooltip += `<br/>科室ID: ${item.id}`;
          }
        }
        
        return tooltip;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '收入金额',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    yAxis: {
      type: 'category',
      data: deptNames,
      axisLabel: {
        interval: 0,
        formatter: (value) => {
          if (value && value.length > 8) {
            return value.substring(0, 8) + '...'
          }
          return value || '未知科室'
        }
      }
    },
    series: [
      {
        name: '收入',
        type: 'bar',
        data: deptValues,
        itemStyle: {
          color: '#91CC75'
        },
        label: {
          show: true,
          position: 'right',
          formatter: '¥{c}'
        }
      }
    ]
  }
  
  deptChart.setOption(option)
  window.addEventListener('resize', () => deptChart.resize())
}

// 加载医生收入排行数据
const loadDoctorRank = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  doctorChartLoading.value = true
  try {
    // 使用静态模拟数据
    const mockData = {
      success: true,
      data: {
        doctors: [
          { doctorId: "001", doctorName: "李医生", departmentName: "内科", title: "副主任医师", totalAmount: 25600 },
          { doctorId: "002", doctorName: "王主任", departmentName: "内科", title: "主任医师", totalAmount: 22400 },
          { doctorId: "003", doctorName: "张医生", departmentName: "外科", title: "主治医师", totalAmount: 19800 },
          { doctorId: "004", doctorName: "刘医生", departmentName: "外科", title: "住院医师", totalAmount: 18500 },
          { doctorId: "005", doctorName: "陈医生", departmentName: "儿科", title: "主任医师", totalAmount: 17200 },
          { doctorId: "006", doctorName: null, departmentName: "妇产科", title: "副主任医师", totalAmount: 16400 },
          { doctorId: "007", doctorName: "杨医生", departmentName: "眼科", title: "主治医师", totalAmount: 14800 },
          { doctorId: "008", doctorName: "黄医生", departmentName: "口腔科", title: "住院医师", totalAmount: 13500 },
          { doctorId: "009", doctorName: "", departmentName: "皮肤科", title: "主治医师", totalAmount: 12300 },
          { doctorId: "010", doctorName: "吴医生", departmentName: "骨科", title: "主任医师", totalAmount: 11600 }
        ],
        values: [25600, 22400, 19800, 18500, 17200, 16400, 14800, 13500, 12300, 11600]
      }
    }
    
    renderDoctorChart(mockData.data)
  } catch (error) {
    console.error('获取医生收入排行数据失败', error)
  } finally {
    doctorChartLoading.value = false
  }
}

// 渲染医生收入排行图
const renderDoctorChart = (data) => {
  if (!doctorChart) {
    doctorChart = echarts.init(doctorChartRef.value)
  }
  
  const doctors = data.doctors || []
  
  // 处理医生名称和数据，确保处理doctorName为null的情况
  const processedDoctors = doctors.map(doctor => {
    let displayName = '未命名医生';
    
    if (doctor.doctorName) {
      displayName = doctor.doctorName;
    } else if (doctor.title && doctor.departmentName) {
      displayName = `${doctor.departmentName}${doctor.title}`;
    } else if (doctor.departmentName) {
      displayName = `${doctor.departmentName}医生`;
    } else if (doctor.title) {
      displayName = doctor.title;
    } else if (doctor.doctorId) {
      displayName = `医生(${doctor.doctorId.substring(0, 6)})`;
    }
    
    return {
      doctor: displayName,
      value: doctor.totalAmount || 0,
      department: doctor.departmentName || '未知科室',
      title: doctor.title || '未知职称',
      id: doctor.doctorId
    };
  });
  
  // 按收入金额排序
  const sortedData = processedDoctors.sort((a, b) => b.value - a.value);
  
  // 取前10个医生
  const top10Data = sortedData.slice(0, 10);
  const doctorNames = top10Data.map(item => item.doctor);
  const doctorValues = top10Data.map(item => item.value);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const idx = params[0].dataIndex;
        const item = top10Data[idx];
        let tooltip = `${params[0].name}<br/>收入: ¥${params[0].value}`;
        
        if (item) {
          if (item.department) {
            tooltip += `<br/>科室: ${item.department}`;
          }
          if (item.title) {
            tooltip += `<br/>职称: ${item.title}`;
          }
          if (item.id) {
            tooltip += `<br/>ID: ${item.id}`;
          }
        }
        
        return tooltip;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '收入金额',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    yAxis: {
      type: 'category',
      data: doctorNames,
      axisLabel: {
        interval: 0,
        formatter: (value) => {
          if (value && value.length > 8) {
            return value.substring(0, 8) + '...'
          }
          return value || '未命名医生'
        }
      }
    },
    series: [
      {
        name: '收入',
        type: 'bar',
        data: doctorValues,
        itemStyle: {
          color: '#5470C6'
        },
        label: {
          show: true,
          position: 'right',
          formatter: '¥{c}'
        }
      }
    ]
  }
  
  doctorChart.setOption(option)
  window.addEventListener('resize', () => doctorChart.resize())
}

// 获取科室选项
const fetchDepartments = async () => {
  try {
    // 使用静态模拟数据
    departmentOptions.value = [
      { id: "D001", name: "内科" },
      { id: "D002", name: "外科" },
      { id: "D003", name: "儿科" },
      { id: "D004", name: "妇产科" },
      { id: "D005", name: "骨科" },
      { id: "D006", name: "眼科" },
      { id: "D007", name: "口腔科" },
      { id: "D008", name: "皮肤科" }
    ]
  } catch (error) {
    console.error('获取科室选项失败', error)
  }
}

// 加载药品收入排行数据
const loadDrugStats = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  drugChartLoading.value = true
  try {
    // 使用静态模拟数据
    const mockData = {
      success: true,
      data: {
        drugs: [
          { drugId: '1', drugName: '阿莫西林胶囊', drugCode: 'YP001', category: '抗生素', specification: '0.25g*24粒', unit: '盒', totalQuantity: 320, prescriptionCount: 280, totalAmount: 6400 },
          { drugId: '2', drugName: '布洛芬片', drugCode: 'YP002', category: '解热镇痛药', specification: '0.2g*24片', unit: '盒', totalQuantity: 280, prescriptionCount: 240, totalAmount: 4200 },
          { drugId: '3', drugName: '头孢克肟胶囊', drugCode: 'YP003', category: '抗生素', specification: '0.1g*12粒', unit: '盒', totalQuantity: 250, prescriptionCount: 210, totalAmount: 8750 },
          { drugId: '4', drugName: '感冒灵颗粒', drugCode: 'YP004', category: '感冒药', specification: '10g*9袋', unit: '盒', totalQuantity: 220, prescriptionCount: 180, totalAmount: 3960 },
          { drugId: '5', drugName: '维生素C片', drugCode: 'YP005', category: '维生素类', specification: '0.1g*100片', unit: '瓶', totalQuantity: 190, prescriptionCount: 150, totalAmount: 2850 },
          { drugId: '6', drugName: '阿司匹林肠溶片', drugCode: 'YP006', category: '解热镇痛药', specification: '0.1g*30片', unit: '盒', totalQuantity: 180, prescriptionCount: 130, totalAmount: 2160 },
          { drugId: '7', drugName: '盐酸氨溴索口服溶液', drugCode: 'YP007', category: '呼吸系统药物', specification: '100ml:0.6g', unit: '瓶', totalQuantity: 150, prescriptionCount: 120, totalAmount: 3750 },
          { drugId: '8', drugName: '硝苯地平缓释片', drugCode: 'YP008', category: '心血管药物', specification: '10mg*30片', unit: '盒', totalQuantity: 130, prescriptionCount: 90, totalAmount: 1950 },
          { drugId: '9', drugName: '奥美拉唑肠溶胶囊', drugCode: 'YP009', category: '消化系统药物', specification: '20mg*14粒', unit: '盒', totalQuantity: 120, prescriptionCount: 100, totalAmount: 2400 },
          { drugId: '10', drugName: '复方甘草片', drugCode: 'YP010', category: '呼吸系统药物', specification: '0.5g*24片', unit: '盒', totalQuantity: 110, prescriptionCount: 80, totalAmount: 880 },
          { drugId: '11', drugName: null, drugCode: 'YP011', category: '消化系统药物', specification: '0.15g*30片', unit: '盒', totalQuantity: 100, prescriptionCount: 70, totalAmount: 1400 },
          { drugId: '12', drugName: '', drugCode: 'YP012', category: '内分泌系统药物', specification: '30mg*30片', unit: '盒', totalQuantity: 90, prescriptionCount: 60, totalAmount: 1800 }
        ]
      }
    }
    
    renderDrugChart(mockData.data)
  } catch (error) {
    console.error('获取药品收入排行数据失败', error)
  } finally {
    drugChartLoading.value = false
  }
}

// 渲染药品收入排行图
const renderDrugChart = (data) => {
  if (!drugChart) {
    drugChart = echarts.init(drugChartRef.value)
  }
  
  const drugs = data.drugs || []
  
  // 处理药品数据，确保处理drugName为null的情况
  const processedDrugs = drugs.map(drug => {
    // 根据统计类型选择要显示的值
    let value = 0
    if (drugStatType.value === 'cost') {
      value = drug.totalAmount || 0
    } else if (drugStatType.value === 'count') {
      value = drug.prescriptionCount || 0
    } else if (drugStatType.value === 'amount') {
      value = drug.totalQuantity || 0
    }
    
    // 修改药品名称显示逻辑: 使用"药品名称(药品代码)"格式
    let displayName
    if (drug.drugName) {
      // 如果有drugCode，则显示"药品名称(药品代码)"
      displayName = drug.drugCode ? `${drug.drugName}(${drug.drugCode})` : drug.drugName
    } else if (drug.drugCode) {
      // 如果只有drugCode，则显示"药品(药品代码)"
      displayName = `药品(${drug.drugCode})`
    } else if (drug.specification) {
      // 如果只有规格，则显示"药品(规格)"
      displayName = `药品(${drug.specification})`
    } else if (drug.category) {
      // 如果只有厂家，则显示"厂家药品"
      displayName = `${drug.category}药品`
    } else {
      // 最后的替代方案
      displayName = `药品(ID:${drug.drugId?.substring(0, 6) || '无ID'})`
    }
    
    return {
      drugName: displayName,
      value: value,
      category: drug.category || '',
      specification: drug.specification || '',
      unit: drug.unit || '',
      drugCode: drug.drugCode || '',
      originalName: drug.drugName,
      prescriptionCount: drug.prescriptionCount || 0,
      totalQuantity: drug.totalQuantity || 0,
      totalAmount: drug.totalAmount || 0,
      id: drug.drugId
    }
  })
  
  // 按值排序
  const sortedData = processedDrugs.sort((a, b) => b.value - a.value)
  
  // 取前10种药品
  const top10Data = sortedData.slice(0, 10)
  const drugNames = top10Data.map(item => item.drugName)
  const drugValues = top10Data.map(item => item.value)
  
  let unit = ''
  let name = ''
  if (drugStatType.value === 'cost') {
    unit = '元'
    name = '收入金额'
  } else if (drugStatType.value === 'count') {
    unit = '次'
    name = '销售次数'
  } else if (drugStatType.value === 'amount') {
    unit = '个'
    name = '销售数量'
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const idx = params[0].dataIndex;
        const item = top10Data[idx];
        let tooltip = `${params[0].name}<br/>${params[0].seriesName}: `;
        
        if (drugStatType.value === 'cost') {
          tooltip += `¥${params[0].value}`
        } else {
          tooltip += `${params[0].value}${unit}`
        }
        
        if (item) {
          if (item.originalName) {
            tooltip += `<br/>药品名称: ${item.originalName}`
          }
          if (item.drugCode) {
            tooltip += `<br/>药品编码: ${item.drugCode}`
          }
          if (item.category) {
            tooltip += `<br/>类别: ${item.category}`
          }
          if (item.specification) {
            tooltip += `<br/>规格: ${item.specification}`
          }
          if (item.unit) {
            tooltip += `<br/>单位: ${item.unit}`
          }
          if (drugStatType.value !== 'cost') {
            tooltip += `<br/>收入金额: ¥${item.totalAmount}`
          }
          if (drugStatType.value !== 'count') {
            tooltip += `<br/>销售次数: ${item.prescriptionCount}次`
          }
          if (drugStatType.value !== 'amount') {
            tooltip += `<br/>销售数量: ${item.totalQuantity}${item.unit || '个'}`
          }
        }
        
        return tooltip;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: name,
      axisLabel: {
        formatter: drugStatType.value === 'cost' ? '¥{value}' : '{value}'
      }
    },
    yAxis: {
      type: 'category',
      data: drugNames,
      axisLabel: {
        interval: 0,
        formatter: (value) => {
          if (value && value.length > 16) {
            return value.substring(0, 16) + '...'
          }
          return value || '未命名药品'
        }
      }
    },
    series: [
      {
        name: name,
        type: 'bar',
        data: drugValues,
        itemStyle: {
          color: function(params) {
            const colorList = [
              '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4',
              '#ea7ccc', '#5470c6', '#91cc75', '#fac858', '#ee6666'
            ]
            return colorList[params.dataIndex % colorList.length]
          }
        },
        label: {
          show: true,
          position: 'right',
          formatter: (params) => {
            if (drugStatType.value === 'cost') {
              return `¥${params.value}`
            } else {
              return `${params.value}${unit}`
            }
          }
        }
      }
    ]
  }
  
  drugChart.setOption(option)
  window.addEventListener('resize', () => drugChart.resize())
}

// 生命周期钩子
onMounted(() => {
  initDateRange()
  fetchDepartments()
  
  nextTick(() => {
    initCharts()
    handleSearch()
  })
})

// 初始化图表
const initCharts = () => {
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value)
  }
  if (categoryChartRef.value) {
    categoryChart = echarts.init(categoryChartRef.value)
  }
  if (paymentMethodChartRef.value) {
    paymentMethodChart = echarts.init(paymentMethodChartRef.value)
  }
  if (deptChartRef.value) {
    deptChart = echarts.init(deptChartRef.value)
  }
  if (doctorChartRef.value) {
    doctorChart = echarts.init(doctorChartRef.value)
  }
  if (drugChartRef.value) {
    drugChart = echarts.init(drugChartRef.value)
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  height: 140px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

.stats-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 15px;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stats-compare {
  position: absolute;
  bottom: 15px;
  right: 20px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.stats-compare .up {
  color: #67C23A;
  margin-left: 5px;
}

.stats-compare .down {
  color: #F56C6C;
  margin-left: 5px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-tools {
  display: flex;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.chart {
  height: 100%;
  width: 100%;
}
</style> 